import { Controller } from 'egg';
import { SuccessResponse } from '../../utils/ResponseBody';
import * as fs from 'fs';
import * as path from 'path';

export default class File extends Controller {
  public async upload() {
    const { ctx } = this;

    const parts = ctx.multipart();
    let part;
    const pathArray: Array<string> = [];
    while ((part = await parts()) != null) {
      if (part.length) {
        // 处理其他参数
        console.log('field: ' + part[0]);
        console.log('value: ' + part[1]);
        console.log('valueTruncated: ' + part[2]);
        console.log('fieldnameTruncated: ' + part[3]);
      } else {
        if (!part.filename) {

          continue;
        }
        // otherwise, it's a stream
        console.log('field: ' + part.fieldname);
        console.log('filename: ' + part.filename);
        console.log('encoding: ' + part.encoding);
        console.log('mime: ' + part.mime);
        const pathName = `uploadfile/${new Date().getTime() + part.filename}`;
        const writePath = path.join('./', pathName);
        const writeStream = fs.createWriteStream(writePath);
        await part.pipe(writeStream);
        pathArray.push('/' + pathName);
      }
    }

    ctx.body = new SuccessResponse({
      paths: pathArray,
    }).toJson();
  }
  public async getFile() {
    const { ctx } = this;
    const { params } = ctx;
    const fileName = params.name;
    const filePath = path.join(process.cwd(), 'uploadfile/' + fileName);
    console.log('filePath', filePath);
    this.ctx.attachment(filePath);
    this.ctx.set('Content-Type', 'application/octet-stream');
    this.ctx.body = fs.createReadStream(filePath);
  }
}
